package com.zmh.thread.muilt_thread_print;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ?????????? ???????????
 *
 * @author zmh
 * @create 2018-10-24 ????11:11
 **/
public class MuiltThreadPrint_lock_condition {

    static Lock reentrantLock = new ReentrantLock();
    static Condition conditionA = reentrantLock.newCondition();
    static Condition conditionB = reentrantLock.newCondition();
    static Condition conditionC = reentrantLock.newCondition();
    static int count = 0;


    static class A extends Thread {
        @Override
        public void run() {
            try {
                int i = 10000;
                while (i > 0) {
                    reentrantLock.lock();
                    while (count % 3 != 0) {
                        conditionA.await();
                    }
                    System.out.println(1);
                    i--;
                    count++;
                    conditionB.signal();
                    reentrantLock.unlock();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    static class B extends Thread {
        @Override
        public void run() {
            try {
                int i = 10000;
                while (i > 0) {
                    reentrantLock.lock();
                    while (count % 3 != 1) {
                        conditionB.await();
                    }
                    System.out.println(2);
                    i--;
                    count++;
                    conditionC.signal();
                    reentrantLock.unlock();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    static class C extends Thread {
        @Override
        public void run() {
            try {
                int i = 10000;
                while (i > 0) {
                    reentrantLock.lock();
                    while (count % 3 != 2) {
                        conditionC.await();
                    }
                    System.out.println(3);
                    i--;
                    count++;
                    conditionA.signal();
                    reentrantLock.unlock();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new A().start();
        new B().start();
        new C().start();
    }
}

